#ifndef __ST7789_H
#define __ST7789_H

#include "main.h"
#include "spi.h"
#include "stdio.h"
#include "string.h"
#include "fonts.h"


#define ST7789_RESET_Pin SPI1_RST_Pin
#define ST7789_RESET_GPIO_Port SPI1_RST_GPIO_Port
#define ST7789_DC_Pin SPI1_DC_Pin
#define ST7789_DC_GPIO_Port SPI1_DC_GPIO_Port
#define ST7789_CS_Pin SPI1_CS_Pin
#define ST7789_CS_GPIO_Port SPI1_CS_GPIO_Port

//MADCTL_MY: Column address is ordered top to bottom.
//MADCTL_MX: Column address is ordered left to right.
//MADCTL_MV: Row address is ordered bottom to top.
//MADCTL_ML: Row address is ordered right to left.
//MADCTL_RGB: The color format is RGB.
//MADCTL_BGR: The color format is BGR.
//MADCTL_MH: The horizontal refresh direction is from right to left.
#define MADCTL_MY  0x80
#define MADCTL_MX  0x40
#define MADCTL_MV  0x20
#define MADCTL_ML  0x10
#define MADCTL_RGB 0x00
#define MADCTL_BGR 0x08
#define MADCTL_MH  0x04

#define ST7789_ROTATION (MADCTL_RGB)

#define DC ST7789_DC_GPIO_Port->BSRR |= ST7789_DC_Pin
#define DCN ST7789_DC_GPIO_Port->BSRR |= ST7789_DC_Pin << 16
#define CS ST7789_CS_GPIO_Port->BSRR |= ST7789_CS_Pin
#define CSN ST7789_CS_GPIO_Port->BSRR |= ST7789_CS_Pin << 16

#define ST7789_SPI_INSTANCE hspi1

#define ST7789_XSTART 0
#define ST7789_YSTART 0
#define ST7789_WIDTH  240
#define ST7789_HEIGHT 320

// Color definitions
#define ST7789_BLACK   0x0000
#define ST7789_BLUE    0x001F
#define ST7789_RED     0xF800
#define ST7789_GREEN   0x07E0
#define ST7789_CYAN    0x07FF
#define ST7789_MAGENTA 0xF81F
#define ST7789_YELLOW  0xFFE0
#define ST7789_WHITE   0xFFFF
#define ST7789_COLOR565(r, g, b) (((r & 0xF8) << 8) | ((g & 0xFC) << 3) | ((b & 0xF8) >> 3))

void ST7789_Init(void);

void ST7789_Pixel(uint16_t x, uint16_t y, uint16_t color);

void ST7789_String(uint16_t x, uint16_t y, char *str, uint16_t color, uint16_t bgColor, const FontDef *font);

void ST7789_Rectangle(uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint16_t color);

void ST7789_Image(uint16_t x, uint16_t y, uint16_t width, uint16_t height, const uint8_t *image);

void ST7789_FillScreen(uint16_t color);

#endif
